#include <stdio.h>
#include <stdlib.h>
#include <alloca.h>
#include <string.h>
#include "san_test.h"

int HeapBufferOverflow()
{
    char* buffer;
    buffer = (char *)malloc(100);
    *(buffer + 101) = 'n';
    *(buffer + 102) = 'n';
    free(buffer);
    printf("address: %p", buffer);
    return buffer[1];
}

int StackBufferOverflow() {
    int subscript = 43;
    char buffer[42];
    buffer[subscript] = 42;
    printf("address: %p", buffer);
    return 0;
}

int StackBufferUnderflow() {
    int subscript = -1;
    char buffer[42];
    buffer[subscript] = 42;
    printf("address: %p", buffer);
    return 0;
}

int HeapUseAfterFree()
{
    int *array = new int[100];
    delete[] array;
    return array[5];
}

int *gp;
bool b = true;
int StackUseAfterScope() {
    if (b) {
        int x[5];
        gp = x + 1;
        printf("address: %p", gp);
    }
    return *gp;
}

int AttempFreeNonAllocatedMem() {
    int value = 42;
    printf("address: %p", &value);
    free(&value);
    return 0;
}

int DoubleFree() {
    int *x = new int[42];
    printf("address: %p", &x);
    delete [] x;
    delete [] x;
    return 0;
}

int HeapBufferUnderflow() {
    char* buffer = (char*)malloc(100);
    // 访问分配内存之前的地址
    *(buffer - 1) = 'A';  // 1字节下溢
    *(buffer - 5) = 'B';  // 5字节下溢
    printf("address: %p, underflow access\n", buffer);
    free(buffer);
    return 0;
}

